﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    TenantManagerViewModel
// 创建者：      杨程
// 创建日期：	    2022/12/16 14:34:35

//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Admin.Server.ViewModels.ViewModel.SystemManager;

/// <summary>
/// 租户管理VM
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.TenantManagerViewModel)]
public partial class TenantManagerViewModel : BillListBaseVM<Sys_Tenant, Sys_Tenant>
{
    private SqlSugarRepository<Sys_Tenant> repTenant { get; set; }

    /// <summary>
    ///
    /// </summary>
    public TenantManagerViewModel( IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_Tenant> _repTenant, SqlSugarRepository<Sys_Tenant> _repSearch) : base(dialog, _repTenant, _repSearch)
    {
        repTenant = _repTenant;
        //构造函数

        //Queryable = dc.Client.Queryable<Sys_Tenant>().OrderBy(o => o.CreateTime);

        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #region [     重写     ]

    protected override void InitVM()
    {
    }

    protected override IUcViewBase SetView()
    {
        switch (ViewKey)
        {
            case ServerViewKeys.EditTenanView:
                return WindowsManager.GetInstance().GetView(ViewKey);

            default:
                throw new NotImplementedException();
        }
    }

    public override void ExecuteBeforeCloseDialogWindow(object obj)
    {
        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #endregion

    #region [     属性     ]

    /// <summary>
    /// 底部页面
    /// </summary>
    [ObservableProperty]
    public IUcViewBase bottomContext;

    private string ViewKey { get; set; }

    #endregion

    #region [     Command命令     ]

    #region [     分页命令     ]

    /// <summary>
    ///     页码改变命令
    /// </summary>
    public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd =>
        new Lazy<RelayCommand<FunctionEventArgs<int>>>(() =>
            new RelayCommand<FunctionEventArgs<int>>(PageUpdated)).Value;

    /// <summary>
    ///     页码改变
    /// </summary>
    private void PageUpdated(FunctionEventArgs<int>? info)
    {
        EntityList.Clear();

        Page = info.Info;

        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #endregion

    /// <summary>
    /// 新增租户命令
    /// </summary>
    [RelayCommand]
    public void AddNewTenant()
    {
        ViewKey = ServerViewKeys.EditTenanView;

        SetDialogWindowSetting(new DialogWindowSetting()
        {
            WindowWidth = 800,
            WindowHeight = 600,
            IsShowMaxButton = false,
            IsShowMinButton = false,
            IsOpenWindowSize = false,
            TitleFontSize = 15,
            CloseDialogWindowCallBackCommand = new RelayCommand<object>(ExecuteBeforeCloseDialogWindow),
            IconStr = "pack://application:,,,/Vampirewal.Admin.Server;component/Logo.png"
        });

        ExecuteShowDialogWindow(null);
    }

    /// <summary>
    /// 查看详细命令
    /// </summary>
    [RelayCommand]
    public void LookDetail(Sys_Tenant tenant)
    {
        BottomContext = WindowsManager.GetInstance().GetView(ServerViewKeys.EditTenanView, Param: tenant);
    }

    #endregion
}

/// <summary>
/// 编辑租户的VM
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.EditTenantViewModel)]
public partial class EditTenantViewModel : BillVM<Sys_Tenant>
{
    private IVampirewalCoreDialogMessage Dialog { get; set; }

    public EditTenantViewModel(IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_Tenant> _repTenant) : base(_repTenant)
    {
        Dialog = dialog;

        RaidoButtonActionsCommand = new IVampirewalCoreEventCommand[]
        {
            //
            new VampirewalCoreEventCommand("Checked","Tag",new RelayCommand<object>((tag) =>
            {
                int day=Convert.ToInt32(tag);

                if (!IsCanEdit)
                {
                    Entity.EndTime=Entity.EndTime.AddDays(day);
                }
                else
                {
                    Entity.EndTime=DateTime.Now.AddDays(day);
                }
            })),
            new VampirewalCoreEventCommand("Unchecked","Tag",new RelayCommand<object>((tag) =>
            {
                int day=-Convert.ToInt32(tag);

                if (!IsCanEdit)
                {
                    Entity.EndTime=Entity.EndTime.AddDays(day);
                }
                else
                {
                    Entity.EndTime=DateTime.Now.AddDays(day);
                }
            })),
        };
    }

    public override void BillVmInitData()
    {
    }

    public override void InitData()
    {
        IsCanEdit = false;
    }

    [ObservableProperty]
    public bool isCanEdit;

    public override void PassData(object obj)
    {
        if (obj == null)
        {
            //新增
            Title = "新增租户";
            //Entity.BillId = Guid.NewGuid().ToString();
            IsCanEdit = true;
        }
        else if (obj is Sys_Tenant dic)
        {
            Title = $"修改 {dic.TenantName} ";
            SetEntity(dic);

            //repDic.ToList(w => w.BillId == dic.BillId).ForEach(DicList.Add);
        }
        else
        {
            CloseView(); ;
        }
    }

    protected override void CloseView()
    {
        WindowsManager.GetInstance().CloseDialogWindow(ViewId);
    }

    public IVampirewalCoreEventCommand[] RaidoButtonActionsCommand { get; set; }

    [RelayCommand]
    public void Save()
    {
        try
        {
            var TopOrg = Rep.Change<Sys_Org>().Single(s => s.ParentId == Guid.Empty.ToString());

            Rep.BeginTran();

            if (string.IsNullOrEmpty(Entity.BillId))
            {
                if (Rep.Any(a => a.Code.Equals(Entity.Code)))
                {
                    //Dialog.ShowPopupWindow($"保存失败！:{Entity.Code} 重复!", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
                    Dialog.ShowPopupWindow(new PopupWindowSetting()
                    {
                        Message= $"保存失败！:{Entity.Code} 重复!",
                        OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                        Type= MessageType.Error
                    });
                    return;
                }

                var model = Rep.InsertReturnEntity(Entity);

                if (model != null)
                {
                    Entity.BillId = model.BillId;

                    #region 新增租户机构

                    Sys_Org TenantOrg = new Sys_Org()
                    {
                        TenantId = Entity.BillId,
                        State = true,
                        CreateBy = "administrator",
                        CreateUserId = Guid.Empty.ToString(),
                        ListId = Guid.NewGuid().ToString(),
                        ParentId = TopOrg.ListId,
                        OrgName = Entity.TenantName,
                        OrgType = 1,
                    };

                    var returnOrg = Rep.Change<Sys_Org>().InsertReturnEntity(TenantOrg);

                    #endregion

                    #region 新增租户管理员

                    Sys_User TenantAdmin = new Sys_User()
                    {
                        TenantId = Entity.BillId,
                        State = 0,
                        CreateBy = "administrator",
                        CreateUserId = Guid.Empty.ToString(),
                        OrgId = returnOrg.BillId,
                        OrgName = returnOrg.OrgName,
                        DepartmentId = returnOrg.BillId,
                        DirectLeaderId = Guid.Empty.ToString(),
                        Email = Entity.AdminEmailAddress,
                        IsCurrentDeptLeader = false,
                        IsAdmin = true,
                        Name = Entity.Code,
                        Gender = 1,
                        Password = Entity.AdminPassWord,
                        PhoneNum = Entity.PhoneNum,
                        open_userid = Entity.Code,
                        Position = "系统管理员",
                        UserId = Entity.Code,
                    };

                    var returnUser = Rep.Change<Sys_User>().InsertReturnEntity(TenantAdmin);

                    #endregion

                    #region 新增用户机构关联表

                    Sys_UserOrg userorg = new Sys_UserOrg()
                    {
                        UserId = returnUser.BillId,
                        OrgId = returnOrg.BillId,
                        Position = " ",
                        CreateBy = "administrator",
                        CreateUserId = Guid.Empty.ToString(),
                    };

                    Rep.Change<Sys_UserOrg>().Insert(userorg);

                    #endregion

                    #region 新增租户字典

                    //Sys_DicCategory Cat1 = new Sys_DicCategory()
                    //{
                    //    DicCategoryName = "性别",
                    //    IsActive = true,
                    //    TenantId = Entity.BillId,
                    //    CreateBy = "administrator",
                    //    CreateUserId = Guid.Empty.ToString(),
                    //    IsPublic
                    //};

                    //var resultCat1= repTenant.Change<Sys_DicCategory>().InsertReturnEntity(Cat1);

                    //Sys_Dic dic1 = new Sys_Dic()
                    //{
                    //    BillId= resultCat1.BillId,
                    //    Description="男",
                    //    DicValue=1,
                    //    IsActive = true,
                    //};

                    //repTenant.Change<Sys_Dic>().Insert(dic1);

                    //Sys_Dic dic2 = new Sys_Dic()
                    //{
                    //    BillId = resultCat1.BillId,
                    //    Description = "女",
                    //    DicValue = 2,
                    //    IsActive = true,
                    //};

                    //repTenant.Change<Sys_Dic>().Insert(dic2);

                    #endregion

                    #region 新增租户管理员角色

                    Sys_RoleTemplate role = new Sys_RoleTemplate()
                    {
                        RoleName = "超级管理员",
                        Code = Entity.Code,
                        IsActive = true,
                        TenantId = Entity.BillId,
                        CreateBy = "administrator",
                        CreateUserId = Guid.Empty.ToString(),
                        IsAdmin = true,
                        OrgId= TenantOrg.BillId
                    };
                    var returnRole = Rep.Change<Sys_RoleTemplate>().InsertReturnEntity(role);

                    #endregion

                    #region 新增用户角色关联表

                    Sys_UserRole userRole = new Sys_UserRole()
                    {
                        UserId = returnUser.BillId,
                        RoleId = returnRole.BillId,
                        CreateBy = "administrator",
                        CreateUserId = Guid.Empty.ToString(),
                    };

                    Rep.Change<Sys_UserRole>().Insert(userRole);

                    #endregion
                }
            }
            else
            {
                Rep.Update(Entity);

                /*
                 * TODO 没想好到底要不要联动更新租户机构和租户管理员的信息，或者就是放到那边去自行修改
                 */
            }

            Rep.CommitTran();

            if (ViewId == Guid.Empty)
                //Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().MainWindow, MessageType.Successful);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = "保存成功!",
                    OwnerWindow = WindowsManager.GetInstance().MainWindow,
                    Type = MessageType.Successful
                });
            else
                //Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Successful);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = "保存成功!",
                    OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type = MessageType.Successful
                });
        }
        catch (Exception ex)
        {
            Rep.RollbackTran();
            if (ViewId == Guid.Empty)
                //Dialog.ShowPopupWindow($"保存失败！:{ex.Message}", WindowsManager.GetInstance().MainWindow, MessageType.Error);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = $"保存失败！:{ex.Message}",
                    OwnerWindow = WindowsManager.GetInstance().MainWindow,
                    Type = MessageType.Error
                });
            else
                //Dialog.ShowPopupWindow($"保存失败！:{ex.Message}", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = $"保存失败！:{ex.Message}",
                    OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type = MessageType.Error
                });
        }
    }
}